from minio import Minio
from minio.error import S3Error
from django.conf import settings

class MinioLib:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(MinioLib, cls).__new__(cls, *args, **kwargs)
        return cls._instance

    def __init__(self) -> None:
        if not hasattr(self, 'initialized'):
            self.host = settings.MINIO['Host']
            self.access_key = settings.MINIO['AccessKey']
            self.secret_key = settings.MINIO['SecretKey']
            self.bucket_name = settings.MINIO['BucketName']
            self.secure = settings.MINIO['Secure']
            
            # 连接 MinIO
            self.client = Minio(self.host, self.access_key, self.secret_key, secure=self.secure, cert_check=False)
            
            # 创建桶
            try:
                if not self.client.bucket_exists(self.bucket_name):
                    self.client.make_bucket(self.bucket_name)
            except S3Error as err:
                print(err)
            
            self.initialized = True

    '''
    上传本地文件
    :object_name    带后缀的文件名
    :file_path      文件上传路径
    '''
    def fput_object(self, object_name, file_path, **kwargs):
        try:
            return self.client.fput_object(self.bucket_name, object_name, file_path, **kwargs)
        except S3Error as err:
            print(err)
    
    '''
    上传流文件对象
    :object_name    带后缀的文件名
    :data           文件对象
    :length         文件大小
    '''
    def put_object(self, object_name, data, length, **kwargs):
        metadata = {
            "name": data.name.encode(),  # 记录文件原名称
        }
        try:
            return self.client.put_object(self.bucket_name, object_name, data, length, metadata=metadata, **kwargs)
        except S3Error as err:
            print(err)

    '''
    获取文件url访问地址
    :object_name    带后缀的文件名
    '''
    def presigned_get_object(self, object_name, **kwargs):
        try:
            return self.client.presigned_get_object(self.bucket_name, object_name, **kwargs)
        except S3Error as err:
            print(err)